<template>
  <!-- 用车记录 -->
  <base-breadcrumb :title="$route.meta.title">
    <!-- 搜索 -->
    <searchData ref="searchData" :search-data="searchArr" @search="search" />
    <!-- 表格 -->
    <a-card :bordered="false">
      <!-- <title-name :title="$route.meta.title" /> -->
      <!-- 导出 -->
      <!-- <excel
        ref="exportAll"
        v-btnPermission="'oa_013_exp_02'"
        style="margin-left: 0"
        class="mb12"
        :file-name="`${exportFileName}_用车记录`"
        is-click-generate="false"
      >
        <a-button
          slot="excelBtn"
          type="primary"
          icon="download"
          :loading="loading"
          @click="exportAll"
        >
          导出
        </a-button>
      </excel> -->
      <!-- 表格 -->
      <list-table ref="table" row-key="id" :columns="columns" :request="loadData" :alert="true" show-size-changer
        show-quick-jumper :export-permission="{ select: 'oa_013_exp_02', all: 'oa_013_exp_02' }"
        :export-config="{ use: true, select: `${exportFileName}_用车记录`, all: `${exportFileName}_用车记录` }">
        <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
        <template slot="action" slot-scope="text, record">
          <!-- 各层级办公室主任、车辆管理员（项目部无该岗位）有权限查看 -->
          <!-- v-if="post === 'COAZR' || post === 'BCAZR' || post === 'PDAZR' || post === 'BCACLGL' || post === 'COACLGL'" -->
          <a v-btnPermission="'oa_013_loo_01'" @click="handleManage(record.id)">查看</a>
        </template>
        <!-- 状态 -->
        <template slot="travelStatus" slot-scope="text, record">
          <status-display :status-code="record.travelStatus" :status-map="statusMap" />
        </template>
      </list-table>
    </a-card>
  </base-breadcrumb>
</template>

<script>
// import { STable } from '@/components' // 表格
import { carApplicationRecord } from '@/api/office/vehicle/config' // api
import SelectCompanyAndProject from '@/components/Select/SelectCompanyAndProject'
import StatusDisplay from '@/components/StatusDisplay'
import OrgTreeSelect from '@/components/OrgTreeSelect'
import BasePage from '@/views/basePage' // 基础配置

const searchArr = [
  // 搜索框
  {
    name: '申请单位',
    valueKey: 'searchQuery',
    type: OrgTreeSelect,
    attr: {
      isAutoSelectFirst: true
    }
  },
  // {
  //   name: '申请单位',
  //   valueKey: 'unitId',
  //   type: SelectCompanyAndProject
  // },
  {
    name: '使用日期',
    type: 'date',
    value: 'useCarTime',
    attr: {
      valueFormat: 'YYYY-MM-DD'
    }
  },
  {
    name: '车牌号',
    type: 'input',
    value: 'car'
  }
]
const columns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    scopedSlots: { customRender: 'index' }
  },
  {
    title: '申请单位',
    ellipsis: true,
    dataIndex: 'unitName'
  },
  {
    title: '申请部门',
    ellipsis: true,
    dataIndex: 'departmentName'
  },
  {
    title: '目的地',
    ellipsis: true,
    dataIndex: 'address'
  },
  {
    title: '预定往返时间',
    dataIndex: 'time',
    width: 290,
    customRender() {
      return arguments[1].goTime && arguments[1].comeTime ? arguments[1].goTime + '至' + arguments[1].comeTime : ''
    }
  },
  {
    title: '用车人数',
    ellipsis: true,
    dataIndex: 'usePersonNum'
  },
  {
    title: '使用车辆',
    dataIndex: 'car',
    width: 290,
    ellipsis: true,
    customRender() {
      let _str = "";
      if (arguments[1].carApplication?.carDispatchRecords?.length > 0) {
        _str = arguments[1].carApplication.carDispatchRecords
          .map((item) => {
            let _str1 = '';
            if (item.carInfo.carNumber) {
              _str1 += `${item.carInfo.carNumber}`;
            }
            if (item.carInfo.driverName || item.carInfo.phone) {
              _str1 += `（${item.carInfo.driverName || ''}${item.carInfo.phone || ''}）`
            }
            return _str1;
          })
      } else {
        _str = "无"
      }
      return _str;
    }
  },
  {
    title: '事由',
    ellipsis: true,
    dataIndex: 'subjectMatter'
  },
  {
    title: '状态',
    dataIndex: 'travelStatus',
    scopedSlots: { customRender: 'travelStatus' }
  },
  {
    title: '实际归队时间',
    ellipsis: true,
    width: 180,
    dataIndex: 'actualTime'
  },
  {
    title: '满意度平均得分(90分)',
    dataIndex: 'score'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '230px',
    fixed: 'right',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'a' + Date.now(),
  extends: new BasePage(),
  components: {
    // STable,
    StatusDisplay
  },
  data() {
    this.columns = columns
    this.searchArr = searchArr
    return {
      loading: false, // 导出loading
      queryParam: {}, // 查询参数
      loadData: (parameter) => {
        // if (!this.init) {
        //   return false
        // }
        const requestParameters = Object.assign({}, parameter, { query: this.queryParam })
        return carApplicationRecord.getList(requestParameters).then((res) => {
          return res
        })
      }, // 加载数据方法 必须为 Promise 对象
      statusMap: {
        0: {
          label: '未开始',
          color: '#00A854'
        },
        1: {
          label: '进行中',
          color: '#ff9900'
        },
        2: {
          label: '已归队',
          color: '#999'
        }
      }, // 状态枚举
      // init: false, // 弹窗初始化标识
      post: '', // 登录人组织code
      exportFileName: '' // 导出文件名
    }
  },
  mounted() {
    this.post = this.$currentPost()?.code
    this.exportFileName = this.$currentPost()?.name
    // this.$refs.exportAll.tableToExcelFile(this.$refs.table, 0)
    this.$refs.searchData.form.setFieldsValue({
      // unitId: this.$currentPost()?.id,
      // searchQuery: {
      //   _checked: this.$currentPost()?.id
      // }
    })
    // this.init = true
    this.search({
      // unitId: this.$currentPost()?.id,
      // searchQuery: {
      //   _checked: this.$currentPost()?.id
      // }
    })
  },
  methods: {
    /**
     * 导出
     */
    exportAll() {
      this.loading = true
      let form = this.$refs.searchData.form.getFieldsValue()
      if (form.time) {
        form.startTime = this.$dateFormat(form.time[0], 'D')
        form.endTime = this.$dateFormat(form.time[1], 'D')
        delete form.time
      }
      carApplicationRecord
        .getAllList(Object.assign({}, { isExport: true }, form))
        .then((res) => {
          this.loading = false
          if (res.data?.length > 0) {
            res.data.forEach((item, index) => {
              item.index = index + 1
              // 格式化预定往返时间
              item.time = item.goTime && item.comeTime ? item.goTime + '至' + item.comeTime : ''
              // 格式化使用车辆
              item.car =
                item.carApplication?.carDispatchRecords?.length > 0
                  ? item.carApplication.carDispatchRecords
                    .map((i) => `${i.carInfo.carNumber}（${i.carInfo.driverName || ''}${i.carInfo.phone}）`)
                    ?.join('；')
                  : ''
              // 格式化状态
              item.travelStatus = ['未开始', '进行中', '已归队'][item.travelStatus]
            })
            console.log(res.data)
            this.$refs.exportAll.setDataAndGenerate(res.data)
            this.$message.success('导出成功')
          } else {
            this.$message.warning('没有数据可以导出')
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    /**
     * 搜索
     */
    search(value) {
      value && (this.queryParam = value)
      this.$refs.table.refresh(true)
    },
    /**
     * 操作栏
     */
    handleManage(id) {
      let query = {
        id
      }
      this.$router.push({
        name: '/vehicle/carRecordEdit',
        query
      })
    }
  }
}
</script>
